package stock.avanza;

import static java.util.Calendar.*;
import ernie.database.Database;
import ernie.database.WebMysql;
import graph.autodrawer.AutoDrawer;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import misc.Helpers;
import stock.Stock;

import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlTable;

public class AvanzaScrape implements Runnable {

    private final Login login;
    private final String targetAddress;
    private final HashMap<String, ScrapeThread> threads;
    private final WebClient client;
    private AutoDrawer autoDrawer;

    public static void main(String[] args) throws IOException {
        new AvanzaScrape().run();
    }

    public AvanzaScrape() {
        login = new Login();
        targetAddress = "127.0.0.1";
        threads = new HashMap<String, ScrapeThread>();
        client = Helpers.createNewAndSilenceWebClient();
        login.makeLoggedIn(client);
    }

    public void setAutoDrawer(AutoDrawer autoDrawer) {
        this.autoDrawer = autoDrawer;
    }

    @Override
    public void run() {
        ArrayList<Stock> followedStocks = new ArrayList<Stock>();
        Database db = new WebMysql(targetAddress, "avslut");

        while (true) {

            Calendar calendarInstance = Calendar.getInstance();
            int hour = calendarInstance.get(HOUR_OF_DAY);
            int day = calendarInstance.get(DAY_OF_WEEK);

            if (day != SATURDAY && day != SUNDAY && 9 <= hour && hour <= 18) {

                ArrayList<Stock> newStocks = getMyFollowedStocks();
                for (Stock stock : newStocks) {
                    if (!followedStocks.contains(stock)) {
                        followedStocks.add(stock);
                        ScrapeThread thread = new ScrapeThread(stock, db,
                                login, autoDrawer);
                        String name = stock.waitForName();
                        threads.put(name, thread);
                        System.out.println("Prenumeration av " + name
                                + " startad");
                    }
                }
            }
            try {
                Thread.sleep(400000);
            } catch (InterruptedException ex) {
            }
        }
    }

    public ScrapeThread getThread(String name) {
        return threads.get(name);
    }

    public ArrayList<Stock> getMyFollowedStocks() {
        ArrayList<Stock> stocks = new ArrayList<Stock>();

        HtmlPage p = null;
        try {
            p = client
                    .getPage("https://www.avanza.se/aza/minavanza/aktiebevakningssida/kursbevakningssida.jsp");

            HtmlTable table = (HtmlTable) p
                    .getByXPath(
                            "/html/body[@class='signedin']/table/tbody/tr[1]/td[1]/table[@class='tablecontent']/tbody/tr/td/table[@class='shareTable']")
                    .get(0);
            for (int i = 1; i < table.getRowCount(); i++) {
                String xml = table.getCellAt(i, 2).asXml();
                xml = xml.substring(93);
                xml = xml.substring(0, xml.indexOf('\"'));
                int id = Integer.valueOf(xml);
                stocks.add(new Stock(id));
            }
        } catch (Exception ex) {
            System.out.println("Failed to get followed stocks, trying again");
            ex.printStackTrace();
            try {
				Thread.sleep(10000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
            return getMyFollowedStocks();
        }
        return stocks;
    }

    public List<String> getMyFollowedStockNames() {
        List<String> stocks = new ArrayList<String>();

        HtmlPage p = null;
        try {
            p = client
                    .getPage("https://www.avanza.se/aza/minavanza/aktiebevakningssida/kursbevakningssida.jsp");

            HtmlTable table = (HtmlTable) p
                    .getByXPath(
                            "/html/body[@class='signedin']/table/tbody/tr[1]/td[1]/table[@class='tablecontent']/tbody/tr/td/table[@class='shareTable']")
                    .get(0);
            for (int i = 1; i < table.getRowCount(); i++) {
                String xml = table.getCellAt(i, 2).asXml();
                xml = xml.substring(xml.indexOf("title=\"") + 7);
                xml = xml.substring(0, xml.indexOf('\"'));

                xml = Helpers.formatName(xml);

                stocks.add(xml);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            System.out
                    .println("Failed to get stock names, retrying in 10 secs");
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
            }
            return getMyFollowedStockNames();
        }
        return stocks;
    }
}
